<template>
  <div>
    <a-card class="card box-radius box-shadow" :bordered="false">
      <div class="elem-layer-right">
        <span class="popover-wrapper">
          <a-popover
            title="表单校验信息"
            overlayClassName="antd-pro-pages-forms-style-errorPopover"
            trigger="click"
            :getPopupContainer="trigger => trigger.parentNode"
          >
            <template slot="content">
              <li
                v-for="item in errors"
                :key="item.key"
                @click="scrollToField(item.key)"
                class="antd-pro-pages-forms-style-errorListItem"
              >
                <a-icon type="cross-circle-o" class="antd-pro-pages-forms-style-errorIcon" />
                <div class>{{ item.message }}</div>
                <div class="antd-pro-pages-forms-style-errorField"></div>
              </li>
            </template>
            <span class="antd-pro-pages-forms-style-errorIcon" v-if="errors.length > 0">
              <a-icon type="exclamation-circle" />
              {{ errors.length }}
            </span>
          </a-popover>
        </span>
        <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
      </div>
      <apply-form ref="applyform" style="clear:both" key="apply-form-add" :showSubmit="false"/>
    </a-card>
  </div>
</template>

<script>
import ApplyForm from './apply/ApplyForm'
import FooterToolBar from '@/components/FooterToolbar'
import { mixin, mixinDevice } from '@/utils/mixin'
import { refOutApplySave } from '@/api/referral'
import { checkPermission } from '@/utils/permissions'
export default {
  name: 'AdvancedForm',
  mixins: [mixin, mixinDevice],
  components: {
    FooterToolBar,
    ApplyForm
  },
  data () {
    return {
      loading: false,
      errors: []
    }
  },
  methods: {
    handleSubmit (e) {
      e.preventDefault()
    },
    // 最终全页面提交
    validate () {
      const {
        $refs: { applyform }
      } = this
      const ApplyForm = new Promise((resolve, reject) => {
        applyform.form.validateFields((err, values) => {
          console.log('values', values)
          //特殊处理；
          for(var key in values){
            //附件
            if(key == 'fileNameList' && values[key].fileList && values[key].fileList.length > 0){
              var arr = [];
              var name = 'uploadList_' + key + '_deleteItems';
              var deleteArr = localStorage.getItem(name) ? JSON.parse(localStorage.getItem(name)) : [];
              values[key].fileList.map((item,index)=>{
                //是上传成功的，且不在删除的列里面
                if(item.response.code == 200 && !deleteArr.find(fileName=>fileName==item.response.fileName)){
                  arr.push(item.response.fileName)
                } 
              })
              values[key] = arr;
            }
          }
          console.log('values处理后', values)
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })

      // clean this.errors
      this.errors = []
      Promise.all([ApplyForm])
        .then(values => {
          const res = values[0]
          const params = Object.assign({}, res, {
            inPlanTime: (res.inPlanTime && typeof res.inPlanTime === 'object' && res.inPlanTime.format('YYYY-MM-DD HH:mm:ss')) || ''
          })
          console.log('表单取值', params)
          this.loading = true
          refOutApplySave(params).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.$message.success('提交成功')
              if (checkPermission('rolloutManage:rolloutCheck')) {
                this.$router.push('/rolloutManage/rolloutCheck')
              } else {
                setTimeout(() => {
                  this.$router.push('/refresh')
                }, 1500)
              }
            } else {
              this.$message.error(res.message)
            }
          }).catch((err) => {
            this.loading = false
            this.$message.error(err.message)
          }).finally(() => {
            this.loading = false
          })
        })
        .catch(() => {
          const errors = Object.assign({}, applyform.form.getFieldsError())
          const tmp = { ...errors }
          this.errorList(tmp)
        })
    },
    // 错误校验反馈列表
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    // 错误定位
    scrollToField (fieldKey) {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`)
      if (labelNode) {
        labelNode.scrollIntoView(true)
      }
    }
  },
  mounted () {
  }
}
</script>

<style lang="less" scoped>
.card {
  margin-bottom: 24px;
}
.popover-wrapper {
   /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
    overflow: auto;
    min-width: 256px;
    max-height: 290px;
    padding: 0;
  }
}
.antd-pro-pages-forms-style-errorIcon {
  margin-right: 24px;
  color: #f5222d;
  cursor: pointer;
  user-select: none;
  i {
    margin-right: 4px;
  }
}
.antd-pro-pages-forms-style-errorListItem {
  padding: 8px 16px;
  list-style: none;
  border-bottom: 1px solid #e8e8e8;
  transition: all .3s;
  cursor: pointer;

  &:hover {
    background: #e6f7ff;
  }
  .antd-pro-pages-forms-style-errorIcon {
    float: left;
    padding-bottom: 22px;
    margin-top: 4px;
    margin-right: 12px;
    color: #f5222d;
  }
  .antd-pro-pages-forms-style-errorField {
    margin-top: 2px;
    color: rgba(0, 0, 0, .45);
    font-size: 12px;
  }
}
</style>
